<script setup>
import { reactive, ref } from 'vue'
import { dayjs, ElMessage } from 'element-plus'
import SelectDealer from './components/SelectDealer.vue'
import * as XLSX from 'xlsx'

// 树 文档https://sangtian152.github.io/vue3-tree-org/demo/#props

const levelOpts = ref([])
async function handleGetLevelOpts() {
  const res = await window.api.getAllDealerLevel()
  console.log(res)
  const colors = [
    '#8085e8',
    '#7cb5ec',
    '#e4d354',
    '#8d4653',
    '#91e8e1',
    '#434348',
    '#90ed7d',
    '#f7a35c',
    '#8085e9',
    '#f15c80'
  ]
  levelOpts.value = res.map((item, index) => {
    return {
      ...item,
      color: colors[index]
    }
  })
}

const filterState = reactive({
  time: [dayjs().format('YYYY-MM-01'), dayjs().format('YYYY-MM-DD')],
  dealerId: ''
})

// 获取有效的分红规则
let dividendRule = []
async function getDividendRule() {
  const res = await window.api.getDividendByIsEnable(1)
  console.log('分红规则数据', res)
  let rules = res[0] || []
  if (rules) {
    dividendRule = await window.api.getDividendDetail(rules.dividend_id)
  }
  await handleGetLevelOpts()
  getUserlist()
}
getDividendRule()

const cloading = ref(false)
const teamMoney = ref(0)
const teamReward = ref(0)
const userNum = ref(0)
const selfMoney = ref(0)
async function computedData() {
  teamMoney.value = 0
  teamReward.value = 0
  userNum.value = 0
  selfMoney.value = 0
  const userCountRes = await window.api.getDealerListCount(selectKey.value || null)
  console.log('总人数', userCountRes)
  userNum.value = userCountRes
  if (dividendRule.length === 0) {
    ElMessage.warning('请配置分红规则')
    return
  }
  cloading.value = true
  // //获取团队业绩
  // const res = await window.api.getDealerPerformance(
  //   selectKey.value,
  //   filterState.time[0],
  //   filterState.time[1]
  // )
  // console.log('团队业绩', res)
  // teamMoney.value = res.rows.money || 0
  // 计算奖金
  // if (dividendRule) {
  //   dividendRule.forEach((_r) => {
  //     if (teamMoney.value < _r.end_money && teamMoney.value >= _r.start_money) {
  //       console.log(teamMoney.value, _r.ratio)
  //       teamReward.value = (teamMoney.value * _r.ratio) / 100
  //     }
  //   })
  // }

  //计算团队业绩和奖金
  const tArr = await window.api.getPerformanceRecordByDealerForDate(
    selectKey.value,
    filterState.time[0],
    filterState.time[1]
  )
  tArr.forEach((i) => {
    teamMoney.value += i.team_money
  })
  console.log('团队业绩', teamMoney.value)

  //判断该用户是否有分红的权利
  console.log('selectItemData', selectItemData.value)

  if (
    selectItemData.value.parent_dealer_id !== 0 &&
    levelOpts.value.some((i) => i.dealer_level_id === selectItemData.value.dealer_level_id&& i.is_dividend)
  ) {
    let temRewardNum = 0 //算奖金的团队业绩
    //获取下该用户是否有等级变更
    const changeLevelRes = await window.api.getDealerLevelChangeRecord(selectKey.value)
    let changeDate = changeLevelRes[0]?.change_date
    console.log('等级变更的日期', changeDate)
    if (changeDate) {
      tArr.forEach((_i) => {
        if (dayjs(dayjs(_i.performance_date)).isAfter(dayjs(changeDate))) {
          temRewardNum += _i.team_money
        }
      })
    } else {
      temRewardNum = teamMoney.value
    }
    // 计算奖金
    if (dividendRule) {
      dividendRule.forEach((_r) => {
        if (temRewardNum < _r.end_money && temRewardNum >= _r.start_money) {
          console.log(temRewardNum, _r.ratio)
          teamReward.value = (temRewardNum * _r.ratio) / 100
        }
      })
    }
  }

  // 获取个人业绩
  const selfRes = await window.api.getDealerPersonPerformance(
    selectKey.value,
    filterState.time[0],
    filterState.time[1]
  )
  console.log('个人业绩', selfRes.rows.money)
  selfMoney.value = selfRes.rows.money || 0

  setTimeout(() => {
    cloading.value = false
  }, 500)
}

function buildDealerTree(dealers) {
  // 创建一个对象来存储所有经销商，便于快速查找
  const dealerMap = {}
  dealers.forEach((dealer) => {
    dealerMap[dealer.dealer_id] = { ...dealer, children: [] }
  })

  // 结果数组
  const result = []

  // 遍历经销商数据，将子经销商添加到对应父经销商的 children 数组中
  dealers.forEach((dealer) => {
    if (dealer.parent_dealer_id === 0) {
      // 如果没有父级经销商，说明是顶级经销商，直接添加到结果数组
      result.push(dealerMap[dealer.dealer_id])
    } else {
      // 否则，找到父级经销商，将当前经销商添加为其子级
      const parentDealer = dealerMap[dealer.parent_dealer_id]
      parentDealer.children.push(dealerMap[dealer.dealer_id])
    }
  })

  return result
}

const treeData = ref(null)
const selectKey = ref('')
const selectItemData = ref(null)
async function getUserlist() {
  const res = await window.api.getDealerAll('', '')
  console.log('所有用户数据', res.rows)
  if (res.rows.length === 0) return
  const treeArr = buildDealerTree(res.rows)
  treeData.value = treeArr?.[0]
  selectKey.value = treeData.value.dealer_id
  selectItemData.value = treeData.value
  computedData()
}

function handleNodeClick(e, data) {
  console.log(data)
  selectKey.value = data.dealer_id
  selectItemData.value = data
  computedData()
}
function handleDealerChange(e) {
  if (e) {
    selectKey.value = e.dealer_id
    selectItemData.value = e
  } else {
    selectKey.value = treeData.value.dealer_id
    selectItemData.value = treeData.value
  }
  computedData()
}

function getNodeColor(e) {
  let color = ''
  levelOpts.value.forEach((item) => {
    if (item.dealer_level_id === e.dealer_level_id) {
      color = item.color
    }
  })
  return `background-color:${color}`
}

//取出当前选择的节点的所有用户
function traverseDealers(dealers, callback) {
  dealers.forEach((dealer) => {
    // 对当前经销商节点执行处理
    callback(dealer)

    // 如果存在子节点，则递归遍历
    if (dealer.children && dealer.children.length > 0) {
      traverseDealers(dealer.children, callback)
    }
  })
}

const exportLoading=ref(false)
async function handleExportData() {
  exportLoading.value=true
  // console.log('当前经销商数据', selectItemData.value, selectKey.value)
  let listData = []
  traverseDealers([{ ...selectItemData.value }], (item) => {
    listData.push(item)
  })

  const promises = listData.map(async (item) => {
    item.teamMoney = 0
    item.teamReward = 0
    item.selfMoney = 0

    // 获取个人业绩
    const selfRes = await window.api.getDealerPersonPerformance(
      item.dealer_id,
      filterState.time[0],
      filterState.time[1]
    )
    item.selfMoney = selfRes.rows.money || 0

    //计算团队业绩和奖金
    const tArr = await window.api.getPerformanceRecordByDealerForDate(
      item.dealer_id,
      filterState.time[0],
      filterState.time[1]
    )
    tArr.forEach((i) => {
      item.teamMoney += i.team_money
    })
    //判断该用户是否有分红的权利

    if (
      item.parent_dealer_id !== 0 &&
      levelOpts.value.some((i) => i.dealer_level_id === item.dealer_level_id && i.is_dividend)
    ) {
      let temRewardNum = 0 //算奖金的团队业绩
      //获取下该用户是否有等级变更
      const changeLevelRes = await window.api.getDealerLevelChangeRecord(item.dealer_id)
      let changeDate = changeLevelRes[0]?.change_date
      console.log('等级变更的日期', changeDate)
      if (changeDate) {
        tArr.forEach((_i) => {
          if (dayjs(dayjs(_i.performance_date)).isAfter(dayjs(changeDate))) {
            temRewardNum += _i.team_money
          }
        })
      } else {
        temRewardNum = item.teamMoney
      }
      // 计算奖金
      if (dividendRule) {
        dividendRule.forEach((_r) => {
          if (temRewardNum < _r.end_money && temRewardNum >= _r.start_money) {
            console.log(temRewardNum, _r.ratio)
            item.teamReward = (temRewardNum * _r.ratio) / 100
          }
        })
      }
    }

    return item
  })

  const resArr = await Promise.all(promises)

  // 设置 Excel 表头
  const headers = ['经销商等级', '经销商名称', '绑定关系', '团队业绩', '奖金', '个人业绩']

  // 将 listData 转换为合适的格式，每项数据对应 '姓名'、'年龄'、'性别'
  const processedData = resArr.map((item) => ({
    经销商等级: item.dealer_level_name,
    经销商名称: item.dealer_name,
    绑定关系: item.parent_dealer_name,
    团队业绩: item.teamMoney,
    奖金: item.teamReward,
    个人业绩: item.selfMoney
  }))

  // 使用 XLSX.utils.json_to_sheet 生成 sheet，添加表头
  const ws = XLSX.utils.json_to_sheet(processedData, { header: headers })

  // 创建新的工作簿
  const wb = XLSX.utils.book_new()
  // 将 sheet 添加到工作簿
  XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')

  // 导出 Excel 文件
  XLSX.writeFile(wb, `${selectItemData.value.dealer_name}${dayjs().format('YYYYMMDD')}.xlsx`)
  exportLoading.value=false
}
</script>

<template>
  <div class="home-page" v-loading="exportLoading" element-loading-text="导出数据，拼命计算中...">
    <div class="top-filter-wrap">
      <div style="width: 350px">
        <el-date-picker
          v-model="filterState.time"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          :clearable="false"
        />
      </div>
      <SelectDealer
        v-model:dealerid="filterState.dealerId"
        style="width: 300px"
        clearable
        @change="handleDealerChange"
      />
      <el-button type="primary" @click="getUserlist">查询</el-button>
      <el-button type="primary" @click="handleExportData">导出</el-button>
    </div>
    <div v-loading="cloading" class="card-wrap">
      <el-card style="flex: 1" shadow="always" header="团队业绩(元)">{{
        formatPrice(teamMoney)
      }}</el-card>
      <el-card style="flex: 1" shadow="always" header="奖金(元)">{{
        formatPrice(teamReward)
      }}</el-card>
      <el-card style="flex: 1" shadow="always" header="总人数">{{ userNum }}</el-card>
      <el-card style="flex: 1" shadow="always" header="个人业绩(元)">{{
        formatPrice(selfMoney)
      }}</el-card>
    </div>
    <div v-if="treeData" class="tree-wrap">
      <ul class="eg-colors">
        <li class="item">
          <span class="b-box select-box"></span>
          <span>当前选中节点</span>
        </li>
        <li v-for="item in levelOpts" :key="item.dealer_level_id" class="item">
          <span class="b-box" :style="{ background: item.color }"></span>
          <span>{{ item.dealer_level_name }}</span>
        </li>
      </ul>
      <vue3-tree-org
        :data="treeData"
        :node-draggable="false"
        :define-menus="[]"
        :props="{
          id: 'dealer_id',
          pid: 'parent_dealer_id',
          label: 'dealer_name',
          expand: 'expand',
          children: 'children'
        }"
        collapsable
        selected-class-name="node-select-box"
        :selected-key="selectKey"
        :center="false"
        :default-expand-level="100"
        @on-node-click="handleNodeClick"
      >
        <template #default="{ node }">
          <el-popover placement="top-start" :width="200">
            <template #reference>
              <div class="node-box" :style="getNodeColor(node.$$data)">
                {{ node.$$data.dealer_level_name }}{{ node.label }}
              </div>
            </template>
            <div>
              <div>地址：{{ node.$$data.dealer_address || '无' }}</div>
              <div>电话：{{ node.$$data.dealer_mobile || '无' }}</div>
              <div>备注：{{ node.$$data.dealer_remark || '无' }}</div>
            </div>
          </el-popover>
        </template>
      </vue3-tree-org>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.home-page {
  .card-wrap {
    margin-top: 20px;
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
  }
  .tree-wrap {
    margin-top: 20px;
    width: 100%;
    background-color: var(--el-bg-color);
    height: calc(100vh - 300px);
    padding: 20px 40px;
    .eg-colors {
      display: flex;
      gap: 0 15px;
      .item {
        display: flex;
        align-items: center;
        .b-box {
          display: inline-block;
          width: 20px;
          height: 20px;
        }
        .select-box {
          background-color: var(--el-color-error);
        }
      }
    }
    .zm-tree-org {
      background: transparent;
    }
    :deep(.zm-tree-handle){
      right: -40px;
    }
    .node-box {
      color: var(--el-color-white);
      font-size: 14px;
      padding: 4px 6px;
      border-radius: 4px;
    }
    .node-select-box {
      .node-box {
        background-color: var(--el-color-error) !important;
        // border: 1px solid var(--el-color-error);
        // box-shadow: var(--el-box-shadow-light);
      }
    }
  }
}
</style>
